/**
 * @author Mie Plougstrup, Anders Abildgaard, Bo Stokholm 
 * @Version 16-12-2014
 */

package ctrLayer;

import java.util.ArrayList;

import modelLayer.Address;
import modelLayer.Supplier;
import modelLayer.Trailer;
import dbLayer.DbConnection;
import dbLayer.DbMaxId;
import dbLayer.DbTrailer;
/**
 * @author Bo Stokholm
 * */
public class CtrTrailer {
	private DbTrailer dbTrail;
	private DbConnection con;
	private CtrAddress ctrAddress;
	private CtrBusinessPartner ctrBp;

	public CtrTrailer(){
		dbTrail = new DbTrailer();
		con = DbConnection.getInstance();
		ctrAddress = new CtrAddress();
		ctrBp = new CtrBusinessPartner();
	}
	/**
	 * Find and returns a trailer object by its trailer id.
	 * @param int id
	 * @return Trailer object
	 */
	public Trailer retrieveTrailer(int id){
		return dbTrail.retrieveById(id);
	}

	public ArrayList<Trailer> retrieveUnusedTrailers(int dispListId) {
		return dbTrail.retrieveUnusedTrailers(dispListId);
	}

	/**
	 * Updates a trailer in the database.
	 * @param Trailer object
	 */
	public void update(Trailer trail){
		dbTrail.update(trail);
	}
	/**
	 * Inserts a trailer object into the database.
	 * @param Trailer trailer
	 */
	public void createWSup(String trailerName, Supplier supplier) throws Exception{
		Trailer t = new Trailer(trailerName, supplier);
		int id = DbMaxId.getMaxID("trailerId", "trailer") + 1;
		t.setTrailerId(id);
		dbTrail.insert(t);
	}
	/**
	 * Deletes a trailer from the database.
	 * @param Trailer trailer
	 */
	public void delete(Trailer trail){
		dbTrail.delete(trail);
	}

	public Trailer retrieveTrailerByName(String name) {
		return dbTrail.retrieveByTrailerName(name);
	}
	public void createWOSup(String trailerName, String supName, String street, String houseNo,
			String postalCode, String city, String supPhone) throws Exception {
		int id = DbMaxId.getMaxID("trailerId", "trailer") + 1;
		try {
			con.startTransaction();
			String country = ctrAddress.retrieveCountryByCode(postalCode);
			Address address = ctrAddress.create("", street, houseNo, postalCode, city, country, 1);
			Supplier supplier = ctrBp.createSupplier(supName, supPhone, address);
			Trailer t = new Trailer(trailerName, supplier);
			t.setTrailerId(id);
			dbTrail.insert(t);
			con.commitTransaction();
		} catch (Exception e) {
			con.rollbackTransaction();
			throw e;
		}
	}

}
